/*
 *
 * 复制拦截器
 *
*/

const copyText = () => {
  return [
    '',
    '作者：于梦中',
    '链接：' + location.href,
    '来源：yumengzhong.com',
    '著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。',
    ''
  ].join('\n')
}
// 拼接成Text
const buildText = content => {
  return content + copyText()
}
// 拼接成html
const buildHtml = content => {
  return content + copyText()
}

export default {
  mounted() {
    this.$root.$copyToClipboard = this.copyToClipboard
    this.listenerCopy()
  },
  methods: {
    copyToClipboard(text) {
      this.clipboardText = text
      // 维护中间量用于给拦截器做标识
      window.clickCopy = true
      setTimeout(() => {
        this.$refs.clipboard.select()
        document.execCommand('Copy')
        window.clickCopy = false
      }, 0)
    },
    listenerCopy() {
      document.addEventListener('copy', e => {
        if (!window.getSelection) return
        if (!window.clickCopy) {
          const content = window.getSelection().toString()
          if (content.length < 100) {
            return
          }
          e.clipboardData.setData('text/plain', buildText(content))
          e.clipboardData.setData('text/html', buildHtml(content))
          e.preventDefault()
        }
      })
    }
  }
}
